package com.zzk.audiovideodemo.mediarecorder

import android.media.MediaPlayer
import android.media.MediaRecorder
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.SystemClock
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.blankj.utilcode.util.LogUtils
import com.zzk.audiovideodemo.R
import kotlinx.android.synthetic.main.activity_mediarecorder_audio.*
import java.io.File
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors


/**
 * MediaRecorder使用实例
 * @author king
 * @time 2020-3-25 9:31
 */
class MediaRecorderAudioActivity : AppCompatActivity() {

    private var mediaPlayer: MediaPlayer? = null
    private var mediaRecorder: MediaRecorder? = null

    //是否正在录制
    private var isRecording = false

    //文件保存位置
    private var mRecorderFile: File? = null

    //
    private var mExecutorService: ExecutorService? = null
    private var startRecorderTime: Long = 0
    private var stopRecorderTime: Long = 0
    private val mHander: Handler = Handler(Looper.getMainLooper())

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_mediarecorder_audio)
        //录音JNI函数不具有线程安全性，因此用单线程
        mExecutorService = Executors.newSingleThreadExecutor();
    }

    /**
     * 开始录制
     */
    fun startRecordMediaRecorderAudio(view: View) {
        //提交后台任务，开始录音
        mExecutorService?.submit { //释放上一次的录音
            releaseRecorder()
            //开始录音
            if (!doStart()) {
                recorderFial()
            }
        }
    }

    /**
     * 释放上一次的录音
     */
    private fun releaseRecorder() {
        if (mediaRecorder != null) {
            mediaRecorder?.release()
            mediaRecorder = null
        }
    }

    /**
     * 开始录音
     */
    private fun doStart(): Boolean {
        if (isRecording) {
            return false
        }
        ct_time.start()
        mediaRecorder = MediaRecorder()
        //创建录音文件
        mRecorderFile = File("${externalCacheDir?.absolutePath}/test.3gp")
        if (mRecorderFile?.getParentFile()?.exists() == false) {
            mRecorderFile?.getParentFile()?.mkdirs()
        }
        mRecorderFile?.createNewFile()
        //设置音频来源，这里是来自麦克风
        mediaRecorder?.setAudioSource(MediaRecorder.AudioSource.MIC)
        //设置输出的音频文件格式,这里设置为3gp
        mediaRecorder?.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP)
        //所有android系统都支持的适中采样的频率
        mediaRecorder?.setAudioSamplingRate(44100)
        //设置音频编码，具体类型查看官网介绍 ,通用的AAC编码格式
        mediaRecorder?.setAudioEncoder(MediaRecorder.AudioEncoder.AAC)
        //设置音质频率
        mediaRecorder?.setAudioEncodingBitRate(96000)
        //设置文件录音的位置
        mediaRecorder?.setOutputFile(mRecorderFile?.getAbsolutePath())
        LogUtils.i("filePath = ${mRecorderFile?.getAbsolutePath()}")

        try {
            //准备
            mediaRecorder?.prepare()
            //开始录制
            mediaRecorder?.start()
            isRecording = true
            startRecorderTime = System.currentTimeMillis();
        } catch (e: Exception) {
            LogUtils.e("mediaRecorder.prepare() failed")
            Toast.makeText(this, "录音失败，请重试", Toast.LENGTH_SHORT).show();
        }
        return true
    }

    /**
     * 录音失败逻辑
     */
    private fun recorderFial() {
        mRecorderFile = null
        mHander.post { tv_press_send.setText("录音失败请重新录音") }
    }


    /**
     * 停止录制
     */
    fun stopRecordMediaRecorderAudio(view: View): Boolean {
        ct_time.stop()
        ct_time.setBase(SystemClock.elapsedRealtime())
        mediaRecorder?.stop()
        //释放资源
        mediaRecorder?.release()
        mediaRecorder = null
        isRecording = false
        stopRecorderTime = System.currentTimeMillis();
        val second = (stopRecorderTime - startRecorderTime) / 1000
        //按住时间小于3秒钟，算作录取失败，不进行发送
        if (second < 3) return false
        mHander.post {
            tv_press_send.setText("录制成功：" + second + "秒");
        }
        return true
    }

    /**
     * 播放音频
     */
    fun startPlayMediaRecorderAudio(view: View) {
        if (mediaPlayer != null && (mediaPlayer?.isPlaying == false)) {
            mExecutorService?.submit { doPlay(view, mRecorderFile); }
        } else {
            Toast.makeText(this, "正在播放", Toast.LENGTH_SHORT).show();
        }
    }

    private fun doPlay(view: View, mRecorderFile: File?) {
        //配置播放器 MediaPlayer
        mediaPlayer = MediaPlayer()
        //设置音频数据来源
        mediaPlayer?.setDataSource(mRecorderFile?.getAbsolutePath())
        LogUtils.i("filePath = ${mRecorderFile?.getAbsolutePath()}")
        //配置音量,中等音量
        mediaPlayer?.setVolume(1F, 1F);
        //播放是否循环
        mediaPlayer?.setLooping(false);

        mediaPlayer?.setOnCompletionListener {
            //播放完毕监听
            LogUtils.i("播放完毕监听")
            stopPlayMediaRecorderAudio(view);
        }
        mediaPlayer?.setOnErrorListener { mp, what, extra ->
            //播放出错监听
            LogUtils.i("播放出错监听")
            stopPlayMediaRecorderAudio(view);
            Toast.makeText(this, "播放失败", Toast.LENGTH_SHORT).show();
            true
        }

        try {
            //缓冲
            mediaPlayer?.prepare()
            //播放
            mediaPlayer?.start()
        } catch (e: Exception) {
            LogUtils.e("mediaPlayer.prepare() failed")
        }
    }

    /**
     * 停止播放
     */
    fun stopPlayMediaRecorderAudio(view: View) {
        mediaPlayer?.stop()
        mediaPlayer?.release()
        mediaPlayer = null
    }

    override fun onStop() {
        super.onStop()
        //当activity关闭时，停止这个线程，防止内存泄漏
        mExecutorService?.shutdownNow();
        releaseRecorder();
    }
}
